// 导入请求
import { sysLogin, sysProfile, sysUserById } from '@/api/user.js'
// 导入操作token的方法
import {
  setToken,
  getToken,
  removeToken,
  setTime,
  removeTime
} from '@/utils/auth.js'
const state = {
  token: getToken(),
  // 用户信息
  userInfo: ''
}
const mutations = {
  // 设置token
  setToken (state, value) {
    state.token = value
    // 保存到浏览器
    setToken(value)
    setTime()
  },
  // 删除token
  remove (state) {
    state.token = null
    removeToken()
    removeTime()
  },
  // 保存用户信息
  setUser (state, val) {
    state.userInfo = val
  },
  // 删除用户信息  导航守卫中通过userInfo里的userId判断是否为登录状态
  // 删除userInfo 也就意味着处于了未登录状态
  removeUser (state) {
    state.userInfo = ''
  }
}
const actions = {
  async getUserToken (store, form) {
    const res = await sysLogin(form)
    // console.log(res)
    store.commit('setToken', res)
  },
  // 获取用户信息
  async getUser (store) {
    const res = await sysProfile()
    const res2 = await sysUserById(res.userId)

    store.commit('setUser', { ...res, ...res2 })
    // console.log({ ...res, ...res2 })
  },
  // 退出时调用
  deleteUser (stroe) {
    stroe.commit('remove')
    stroe.commit('removeUser')
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
